﻿using Microsoft.AspNetCore.Mvc;
using Stu_sys.Entity;
using Stu_sys.Models;
using Stu_sys.utils;
using System.Text.Json;

namespace Stu_sys.Controllers
{
    public class SubjectController : Controller
    {
        private readonly MysqlContext _mysqlContext;
        public SubjectController(MysqlContext mysqlContext) 
        { 
            _mysqlContext = mysqlContext;
        }
        public IActionResult SubjectList()
        {
            return View();
        }

        [HttpGet]
        public IActionResult GetSubjectList() 
        {
            var attrStr = MyUtils.GetAttributeToJsonStr(typeof(SubjectViewModel));
            var subjectList = _mysqlContext.Subjects.ToList();
            var subjectStr = JsonSerializer.Serialize(subjectList);
            var data = new
            {
                attr = attrStr,
                row = subjectStr
            };
            return Json((data));
        }

        [HttpPost]
        public IActionResult AddSubject(Subject subject)
        {
            if (subject.SubjectName == "" || subject.SubjectName == "")
            {
                return Json(-1);
            }
            bool isExist = IsExistSubject(subject);
            if (isExist)
            {
                return Json(0);
            }
            _mysqlContext.Subjects.Add(subject);
            var res = _mysqlContext.SaveChanges();
            return Json(res);
        }

        [HttpPost]
        public IActionResult EditSubject(Subject subject)
        {
            if (subject.SubjectName == "")
            {
                return Json(-1);
            }

            var sub = _mysqlContext.Subjects.Where(s=> s.SubjectId == subject.SubjectId).FirstOrDefault();
            sub.SubjectName = subject.SubjectName;


            _mysqlContext.Subjects.Update(sub);
            var res = _mysqlContext.SaveChanges();
            return Json(res);
        }

        [HttpPost]
        public IActionResult DelSubject(Subject subject)
        {
            if (subject == null)
            {
                return Json(-1);
            }
            var d = _mysqlContext.Subjects.Single(s => s.SubjectId == subject.SubjectId);
            _mysqlContext.Remove(d);
            var res = _mysqlContext.SaveChanges();
            return Json(res);
        }

        /// <summary>
        /// 部门是否已存在
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        private bool IsExistSubject(Subject subject)
        {
            var roles = _mysqlContext.Subjects.Where(s => s.SubjectName == subject.SubjectName ).ToList();
            if (roles.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
